import java.util.Date;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.logging.Level;
import javax.activation.MimetypesFileTypeMap;

/**
 * This class is used to read files requested by
 * a client.
 *
 * @author Marlon Etheredge
 * @author <a href="mailto:m.etheredge@gmail.com">m.etheredge@gmail.com</a>
 * @author <a href="http://www.foxage.nl/">http://www.foxage.nl</a>
 */
public class FileHandler {

	/** File to read. */
	private File file;

	/** Path of htdocs set in confiruation file read from Webster class. */
	private static String htdocsPath = Webster.getProperty("htdocspath");

	/** MIME Type of File to handle */
	private String mimeType;

	/**
	 * Constructs a new FileHandler instance.
	 *
	 * @param fileName File to associate with this FileHandler instance
	 */
	public FileHandler(String fileName) throws FileNotFoundException {
		this.file = new File(htdocsPath + "/" + (fileName.equals("/") ? Webster.getProperty("rootURI") : fileName));
	}

	/** 
	 * Reads a File out of the htdocs path,
	 * and returns the contents of this File.
	 *
	 * @return Contents of the File
	 */
	public byte[] readFile() throws IOException, FileNotFoundException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(this.file));
                
        byte[] fileBytes = new byte[bufferedInputStream.available()];
        bufferedInputStream.read(fileBytes);
		
		return fileBytes;
	}
	
	/**
	 * Returns the last modified date of the File for
	 * this FileHandler instance.
	 *
	 * @return Date Last modified date
	 */
	public Date getLastModifiedDate() {
		return new Date(file.lastModified());  
	}
	
	/**
	 * Returns the MIME type of the file associated with
	 * this instance of FileHandler.
	 *
	 * @return String The MIME type
	 */
	public String getMimeType() {
		return (String) new MimetypesFileTypeMap().getContentType(file);
	}

	/**
	 * Sets the htdocs path.
	 *
	 * @param path Path to the htdocs directory
	 */
	public static void setHtdocs(String path) {
		htdocsPath = path;
	}

}
